﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Printing;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Printing;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace pintu
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class ManagerFolderPicturePage : Page
    {
        public ManagerFolderPicturePage()
        {
            this.InitializeComponent();
            printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
        }
        ObservableCollection<BitmapImage> bitmaplist = new ObservableCollection<BitmapImage>();
        protected  override async  void OnNavigatedTo(NavigationEventArgs e)
        {
            var list = (IReadOnlyList<StorageFile>)e.Parameter;
            foreach(var  a in list)
            {
                IRandomAccessStream irandom = await a.OpenAsync(FileAccessMode.Read);
                //对图像源使用流源
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(irandom);
                bitmaplist.Add(bitmapImage);
            }
            control.ItemsSource = bitmaplist;
            base.OnNavigatedTo(e);
        }
        /// <summary>  
            /// 使用PrintManage.GetForCurrentView()获取一个PrintManager对象  
            /// PrintManage 打印机管理器是负责为Windows应用程序安排打印流  
            /// 使用时必须调用PrintManager.GetForCurrentView()方法来返回特定于当前窗口的PrintManager  
            /// </summary>  
        PrintManager printmgr = PrintManager.GetForCurrentView();

        /// <summary>  
            /// PrintDocument 将打印流发送到打印机的一个可重用对象  
            /// </summary>  
        PrintDocument printDoc = null;

        /// <summary>  
            /// RotateTransform 是来旋转打印元素的，如果设备是横着的则需要旋转90°  
            /// </summary>  
        RotateTransform rottrf = null;

        /// <summary>  
            /// 表示包括要打印的内容以及提供对描述将如何打印内容的信息的访问的打印操作  
            /// </summary>  
        PrintTask task = null;

    

        private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
        {
            //从参数的Request属性中获取与PrintTaskRequest的任务关联  
            //创建好打印内容和任务后 在调用Complete方法进行打印  
            var deferral = args.Request.GetDeferral();
            // 创建打印任务  
            task = args.Request.CreatePrintTask("购物信息-打印单", OnPrintTaskSourceRequrested);
            task.Completed += PrintTask_Completed;
            deferral.Complete();
        }

        private void PrintTask_Completed(PrintTask sender, PrintTaskCompletedEventArgs args)
        {
            //打印完成  
        }

        private async void OnPrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
        {
            var def = args.GetDeferral();
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            () =>
            {
    // 设置打印源  
    args.SetSource(printDoc?.DocumentSource);
            });
            def.Complete();
        }

        private async void appbar_Printer_Click(object sender, RoutedEventArgs e)
        {
            if (printDoc != null)
            {
                printDoc.GetPreviewPage -= OnGetPreviewPage;
                printDoc.Paginate -= PrintDic_Paginate;
                printDoc.AddPages -= PrintDic_AddPages;
            }
            this.printDoc = new PrintDocument();
            //订阅预览事件  
            printDoc.GetPreviewPage += OnGetPreviewPage;
            //订阅预览时 打印参数发生变化事件 比如文档方向  
            printDoc.Paginate += PrintDic_Paginate;
            //添加页面处理事件  
            printDoc.AddPages += PrintDic_AddPages;

            // 显示打印对话框  
            bool showPrint = await PrintManager.ShowPrintUIAsync();
        }

        //添加打印页面的内容  
        private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
        {
            //增加一个页要打印的元素  
            printDoc.AddPage(control);

            //完成对打印页面的增加  
            printDoc.AddPagesComplete();
        }

        private void PrintDic_Paginate(object sender, PaginateEventArgs e)
        {
            PrintTaskOptions opt = task.Options;
            // 根据页面的方向来调整打印内容的旋转方向  
            //switch (opt.Orientation)
            //{
            //    case PrintOrientation.Default:
            //        rottrf.Angle = 0d;
            //        break;
            //    case PrintOrientation.Portrait:
            //        rottrf.Angle = 0d;
            //        break;
            //    case PrintOrientation.Landscape:
            //        rottrf.Angle = 90d;
            //        break;
            //}

            // 设置预览页面的总页数  
            printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
        }

        private void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
        {
            // 设置要预览的页面  
            printDoc.SetPreviewPage(2, control);
        }

        private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            if(control!=null)
            control.ItemHeight = (sender as Slider).Value;
        }

        private void widthSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            if (control != null)
                control.DesiredWidth = (sender as Slider).Value;
        }

        private async void appbar_save_Click(object sender, RoutedEventArgs e)
        {
           bool  r= await  SavepictureHelper.SavepicwithUielement(control);
            if(r)
            {
                messagetb.Text = "保存成功";
            }
        }

        private async void appbar_choosemultpic_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker picker = new FileOpenPicker();
            picker.FileTypeFilter.Add("*");
            picker.ViewMode = PickerViewMode.List;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            var filelist = await picker.PickMultipleFilesAsync();
            if (filelist != null)
            {
                foreach (var a in filelist)
                {
                    IRandomAccessStream irandom = await a.OpenAsync(FileAccessMode.Read);
                    //对图像源使用流源
                    BitmapImage bitmapImage = new BitmapImage();
                    await bitmapImage.SetSourceAsync(irandom);
                    bitmaplist.Add(bitmapImage);
                }
                control.ItemsSource = bitmaplist;
            }
        }
    }
}
